package org.example.Utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class StringUtils {


    private static DecimalFormat df = null;
    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    static {

        // 设置数字格式，保留一位有效小数
        df = new DecimalFormat("#0.0");
        df.setRoundingMode(RoundingMode.HALF_UP);
        df.setMinimumFractionDigits(1);
        df.setMaximumFractionDigits(1);
    }

    public static String getIp(SocketAddress socketAddress) {
        return socketAddress.toString().split(":")[0];
    }

    public static Integer getNext() {
        return atomicInteger.addAndGet(1);
    }



    public static String getFileName(String in) {
        File file = new File(in);
        return file.getName();
    }

    public static File hasFile(String fileName) throws FileNotFoundException {
        Path file = Paths.get(fileName);
        if (!Files.exists(file)) {
            throw new FileNotFoundException();
        }
        return file.toFile();
    }

    public static String[] InstructionParsing(String in) {
        in = in.trim();
        //获取两个空格的索引
        int index = in.indexOf("  ");
        while (index != -1) {
            //字符串拼接
            in = in.substring(0, index).concat(in.substring(index + 1));
            index = in.indexOf("  ");
        }
        return in.split(" ");
    }

    //提取参数，不做检查
    public static HashMap<String, String> processCommand(String in) {
        if (in == null) return null;
        //空格删除
        String[] args = InstructionParsing(in);

        HashMap<String, String> commandMap = new HashMap<>();

        commandMap.put("start", args[0]);

        for (String arg : args) {
            if (arg.startsWith("-") && !arg.endsWith("-")) {
                int strIndex = findStrIndex(args, arg);
                if (strIndex != args.length - 1 && !args[strIndex + 1].startsWith("-")) {
                    commandMap.put(arg, args[strIndex + 1]);
                } else {
                    commandMap.put(arg, arg);
                }
            }
        }

        return commandMap;
    }



    public static int findStrIndex(String[] args, String str) {
        if (args.length == 0 || str == null) return -1;
        int i = 0;
        for (; i < args.length; i++) {
            if (str.equals(args[i])) return i;
        }
        return -1;
    }


    public static String getFormatFileSize(long length) {
        double size = ((double) length) / (1 << 30);
        if (size >= 1) {
            return df.format(size) + "GB";
        }
        size = ((double) length) / (1 << 20);
        if (size >= 1) {
            return df.format(size) + "MB";
        }
        size = ((double) length) / (1 << 10);
        if (size >= 1) {
            return df.format(size) + "KB";
        }
        return length + "B";
    }

    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static List<String> getTimeUnit(String regular) {
        int index = 0;
        for (int i = 0; i < regular.length(); i++) {
            char c = regular.charAt(i);
            if (Character.isDigit(c)) {
                if (i == regular.length() - 1) {
                    index = i + 1;
                } else {
                    index = i;
                }
            } else {
                index = i;
                break;
            }
        }
        return Arrays.asList(regular.substring(0, index), regular.substring(index));
    }

    public static String getCode() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Base64.Encoder encoder = Base64.getEncoder();
        String encoderStr = null;
        encoderStr = encoder.encodeToString(formatter.format(new Date(System.currentTimeMillis())).getBytes(StandardCharsets.UTF_8));
        return encoderStr;
    }

    public static boolean decode(String code) {
        Base64.Decoder decoder = Base64.getDecoder();
        String decoderStr = new String(decoder.decode(code), StandardCharsets.UTF_8);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return decoderStr.equals(formatter.format(new Date(System.currentTimeMillis())));
    }
}
